<template>
	<div class="bigDiv">
		<el-form :inline="true" :model="queryParams" label-width="88px">
			<div class="topNav">
				排序:
				<el-button type="text" @click="handleOrder('goodsPrice')">
					优采销售价
					<i class="el-icon-top el-icon--right" v-if="queryOrder.goodsPrice == 1"></i>
					<i class="el-icon-bottom el-icon--right" v-if="queryOrder.goodsPrice == 2"></i>
				</el-button>
				<el-button type="text" @click="handleOrder('officialPrice')">
					官网价
					<i class="el-icon-top el-icon--right" v-if="queryOrder.officialPrice == 1"></i>
					<i class="el-icon-bottom el-icon--right" v-if="queryOrder.officialPrice == 2"></i>
				</el-button>
				<el-button type="text" @click="handleOrder('agreementPrice')">
					协议价
					<i class="el-icon-top el-icon--right" v-if="queryOrder.agreementPrice == 1"></i>
					<i class="el-icon-bottom el-icon--right" v-if="queryOrder.agreementPrice == 2"></i>
				</el-button>
				<el-button type="text" @click="handleFailAll" :disabled="listButtonClick" style="float:right;">批量驳回</el-button>
				<el-button type="text" icon="el-icon-search" @click="handleSearch" style="float:right;">搜索</el-button>
			</div>
			<el-form-item label="商品名称" prop="goodsName">
				<el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable size="small" clearable
					@keyup.enter.native="handleSearch" />
			</el-form-item>
			<el-form-item label="品牌" prop="brand">
				<el-select v-model="queryParams.brandId" filterable clearable remote size="small"
					:remote-method="remoteMethod" @change="changeBrand" placeholder="请输入关键词">
					<el-option v-for="item in brandList" :key="item.id" :label="item.nameShow" :value="item.id">
						{{ item.nameShow }}
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="sku" prop="sku">
				<el-input v-model="queryParams.sku" placeholder="sku" clearable size="small" clearable
					@keyup.enter.native="handleSearch" />
			</el-form-item>
			<el-form-item label="电商" prop="supplierId">
				<el-select size="small" v-model="queryParams.supplierId" placeholder="请选择一个电商" filterable clearable>
					<el-option v-for="item in supplierList" :key="item.id" :label="item.orgNameZh" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<lthirdselect @change="changeCategory"></lthirdselect>
		</el-form>


		<el-table ref="multipleTable" v-loading="loading" :data="list" @selection-change="handleSelectionChange" border height="calc(100vh - 360px)"
			:row-class-name="tableRowClassName" class="table">
			<el-table-column type="selection" fixed width="55"></el-table-column>
			<el-table-column label="商品名称" align="center" prop="goodsName" width="250" sortable>
				<template slot-scope="scope">
					<el-tooltip :content="scope.row.goodsName" placement="bottom" effect="dark" class="goodsNameBox">
						<div>{{ scope.row.goodsName }}</div>
					</el-tooltip>
				</template>
			</el-table-column>

			<el-table-column label="商品分类" align="center" width="350">
				<template slot-scope="scope">
					{{ scope.row.primaryCategoryName }}
					<span class="divider">/</span>
					{{ scope.row.secondaryCategoryName }}
					<span class="divider">/</span>
					{{ scope.row.tertiaryCategoryName }}
				</template>
			</el-table-column>
			<el-table-column label="计量单位" align="center" prop="saleUnit" />
			<el-table-column label="优采销售价(元)" align="center" prop="goodsPrice" width="88">
				<template slot-scope="scope">
					<span class="price">
						{{ priceCalc(scope.row.goodsPrice) }}
					</span>
				</template>
			</el-table-column>
			<el-table-column label="优采未税价(元)" align="center" prop="excludeTaxPrice" width="88">
				<template slot-scope="scope">
					{{ priceCalc(scope.row.excludeTaxPrice) }}
				</template>
			</el-table-column>
			<el-table-column label="官网价(元)" align="center" prop="officialPrice">
				<template slot-scope="scope">
					<span class="price">
						{{ scope.row.officialPrice }}
					</span>
				</template>
			</el-table-column>
			<el-table-column label="协议价(元)" align="center" prop="goodsPrice" width="88">
				<template slot-scope="scope">
					<span>
						{{ priceCalc(scope.row.agreementPrice) }}
					</span>
				</template>
			</el-table-column>
			<el-table-column label="折扣率" align="center" width="88" sortable>
				<template slot-scope="scope">
					{{ discountRateCalc(scope.row) }}
				</template>
			</el-table-column>
			<el-table-column label="电商未税价(元)" align="center" prop="excludeTaxPrice" width="88">
				<template slot-scope="scope">
					<span>
						{{ priceCalc(scope.row.initExcludeTaxPrice) }}
					</span>
				</template>
			</el-table-column>
			<el-table-column label="品牌" align="center" prop="brandName" width="180" />
			<el-table-column label="sku" align="center" prop="sku" width="150" />
			<el-table-column label="库存" align="center" prop="goodsStock" />
			<el-table-column label="供应商" align="center" prop="supplierName" width="200" />
			<el-table-column label="申请时间" align="center" prop="updateTime" width="100" />


			<el-table-column label="操作" fixed="right" width="200">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleInfo(scope.row)">审批
					</el-button>

					<!-- el-button size="mini" type="text" icon="el-icon-plus" @click="handlePush(scope.row)">提交审批
					</el-button> -->

					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleGoodsFail(scope.row)">驳回
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0 " :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList"
			:pageSizes="[10, 20, 30, 50, 100, 150, 200, 300]" />

		<el-dialog :title="detailTitle" :visible.sync="dialogDetailVisible" width="80vw" v-loading="dialogLoading">
			<goodsInfoBox ref="info" :info="info" :disabel="disabel"></goodsInfoBox>
			<template slot="footer" class="dialog-footer">
				<el-button size="mini" type="text" icon="el-icon-delete" @click="handleGoodsFail(info)">驳回
				</el-button>
				<el-button size="mini" type="primary" @click="handlePush(info)">提交审批
				</el-button>
			</template>
		</el-dialog>
		
		<el-dialog :title="goodsFailInfoTitle" :visible.sync="goodsFailVisible">
			<template solt="body">
				<el-form label-width="88px">
					<el-form-item label="驳回原因" prop="goodsName">
						<el-input v-model="goodsFailInfo" placeholder="请输入驳回原因" clearable size="small" clearable
							@keyup.enter.native="handleSearch" />
					</el-form-item>
					<el-form-item label="驳回原因" prop="brand">
						<el-select v-model="goodsFailInfo" filterable clearable remote size="small"
							:remote-method="remoteMethod" @change="changeBrand" placeholder="请输入关键词">
							<el-option label="商品分类错误" value="商品分类错误">商品分类错误</el-option>
							<el-option label="商品参数不全/错误" value="商品参数不全/错误">商品参数不全/错误</el-option>
							<el-option label="商品详情介绍过少" value="商品详情介绍过少">商品详情介绍过少</el-option>
							<el-option label="品牌信息错误" value="品牌信息错误">品牌信息错误</el-option>
							<el-option label="价格过高/平台已有价格更低同型号商品" value="价格过高/平台已有价格更低同型号商品">价格过高/平台已有价格更低同型号商品</el-option>
							<el-option label="商品图片不清晰/展示细节不全" value="商品图片不清晰/展示细节不全">商品图片不清晰/展示细节不全</el-option>
						</el-select>
					</el-form-item>
					
				</el-form>
			</template>
			
			<template slot="footer" class="dialog-footer">
				<el-button size="mini" type="text" @click="cancelGoodsFail">取消
				</el-button>
				<el-button size="mini" type="primary" @click="doGoodsFail">确认
				</el-button>
			</template>
		</el-dialog>

		<el-dialog title="批量驳回" :visible.sync="dialogReimportVisible" width="30%" :before-close="stopReimport">
			<el-progress :percentage="percentage" text-inside :stroke-width="20"></el-progress>
			<div style="text-align: center;">
				<span>已驳回 {{ count }}/{{ reImportTotal }}</span>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="stopReimport">取 消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import { goodsListPush, goodsPush, goodsInfo, goodsPushAll, goodsFail, goodsPrice } from "@/api/activiti/goods"
	import { supplierList } from '@/api/supplierActivity/definition'
	import { searchBrands } from "@/api/brand.api";
	import goodsInfoBox from "@/views/supplierActivity/components/goodsInfoBox"
	import lthirdselect from "@/components/l-third-select";
	import tools from "@/tools"

	export default {
		name: "pushGoods",
		components: {
			goodsInfoBox,
			lthirdselect
		},
		data() {
			return {
				list: [],
				supplierList: [],
				brandList: [],
				loading: true,
				total: 0,
				multipleSelection: [],
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					brandId: undefined,
					goodsName: undefined,
					sku: undefined,
					supplierId: undefined,
					primaryCategory: undefined,
					secondaryCategory: undefined,
					tertiaryCategory: undefined,
					// updateTime: "2022-11-18 00:00:00"
				},
				queryOrder: {
					goodsPrice: 0,
					officialPrice: 0,
					agreementPrice: 0
				},
				dialogDetailVisible: false,
				dialogLoading: false,
				detailTitle: "",
				info: {},
				imgList: [],
				disabel: true,
				stop: false,
				count: 0,
				dialogReimportVisible: false,
				reImportList: [],
				loadingSize: 0,
				goodsFailVisible: false,
				goodsFailInfoTitle: "",
				goodsFailInfo: ""
			}
		},
		mounted() {
			this.getList();
			this.getSupplierList();
		},
		computed: {
			reImportTotal() {
				return this.multipleSelection.length
			},
			percentage() {
				if (this.count == 0) return 0
				return parseFloat(((this.count / this.multipleSelection.length) * 100).toFixed(2))
			},
			listButtonClick() {
				return this.multipleSelection.length <= 0;
			}
		},
		methods: {
			getList() {
				goodsListPush({...this.queryParams, ...this.queryOrder}).then(res => {
					this.loadingSize = 0;
					this.total = res.total;
					this.list = res.rows.map(row => {
						if (row.goodsPrice == null || row.goodsPrice == "") {
							this.loadingSize++
							goodsPrice(row.supplierId, row.sku).then(res => {
								row.goodsPrice = res.goodsPrice
								row.excludeTaxPrice = res.excludeTaxPrice
								this.loadingSize--;
								if (this.loadingSize <= 0) {
									this.getList();
								}
							})
						}
						return row;
					});;
					this.loading = false;
				})
			},
			/** 获取电商列表 */
			getSupplierList() {
				supplierList().then(res => {
					this.supplierList = res;
				})
			},
			handleSearch() {
				this.getList();
			},
			handleInfo(row) {
				this.info = {};
				this.dialogLoading = true;
				this.dialogDetailVisible = true;
				this.detailTitle = `${row.goodsName} : ${row.sku}`
				this.disabel = true
				goodsInfo(row.supplierId, row.sku).then(res => {
					this.info = res;
					if (res.goodsImageList) {
						this.imgList = res.goodsImageList.split(',');
					}
					this.dialogLoading = false;
				})
			},
			handlePush(row) {
				this.$confirm(`确认提交商品：${row.goodsName}？`)
					.then(_ => {
						row.goodsIntroduce = null;
						const params = {
							id: row.id,
							sku: row.sku,
							supplierId: row.supplierId,
							supplierName: row.supplierName
						}
						goodsPush(params).then(res => {
							this.dialogDetailVisible = false;
							this.$message.success({
								message: "提交成功"
							})
							this.getList();
						})
					})
					.catch(_ => {});
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 批量提交
			handlePushAll() {
				if (this.multipleSelection.length <= 0) {
					return this.$message.error({
						message: "还未选择任何数据"
					})
				}
				this.$confirm('确认提交审核所选商品？')
					.then(_ => {
						goodsPushAll(this.multipleSelection).then(res => {
							this.dialogDetailVisible = false;
							this.$message.success({
								message: "提交成功"
							})
							this.getList();
						})
					})
					.catch(_ => {});
			},
			// 批量驳回
			handleFailAll() {
				if (this.multipleSelection.length <= 0) {
					return this.$message.error({
						message: "还未选择任何行"
					})
				}
				this.goodsFailVisible = true;
				this.goodsFailInfoTitle = "批量驳回"
				this.info = {};
			},
			startFailAll() {
				const info = this.goodsFailInfo
				setTimeout(() => {
					if (!this.stop) {
						const row = this.reImportList.shift();
						goodsFail(row.supplierId, row.sku, info).then(res => {
							if (res.code == 200) {
								this.count++;
							}
							if (this.reImportList.length > 0) {
								this.startFailAll();
							} else {
								this.stopReimport()
								this.$message.closeAll()
								this.$message.success({
									message: `操作完成, ${this.reImportTotal - this.count} 个失败。`
								})
							}
						}).catch(err => {
							this.stopReimport()
							this.$message.closeAll()
							this.$message.error({
								message: `操作中断, 第 ${this.count + 1} 个失败。`
							})
						})
					}
				}, 1000)
			},
			stopReimport() {
				this.stop = true
				this.dialogReimportVisible = false
				this.count = 0;
				this.multipleSelection = [];
				this.reImportList = [];
				this.$refs.multipleTable.clearSelection();
				this.$message.error({
					message: "已停止"
				})
				this.getList();
			},
			handleGoodsFail(row) {
				this.goodsFailInfoTitle = `驳回商品${row.goodsName}`;
				this.info= row;
				this.goodsFailVisible = true;
			},
			cancelGoodsFail() {
				this.goodsFailVisible = false;
				this.info = {}
			},
			doGoodsFailAll() {
				this.dialogReimportVisible = true;
				this.reImportList = [...this.multipleSelection];
				this.stop = false;
				this.goodsFailVisible = false;
				this.startFailAll();
			},
			doGoodsFail() {
				const row = this.info
				var arr = Object.keys(row);
				if(arr.length == 0) {
					// 批量操作
					this.doGoodsFailAll();
					return;
				}
				if (this.goodsFailInfo == null || this.goodsFailInfo == '') {
					this.$message({
						type: 'info',
						message: `请输入原因，驳回：${row.goodsName}`
					});
					return;
				}
				goodsFail(row.supplierId, row.sku, this.goodsFailInfo).then(res => {
					this.goodsFailVisible = false;
					this.$message.success({
						message: "驳回成功"
					})
					this.info = {};
					this.getList();
				})
			},
			remoteMethod(query) {
				if (query !== '') {
					searchBrands(query).then(res => {
						this.brandList = res
					})
				}
			},
			changeBrand(brand) {
				this.brandList.map(row => {
					if (row.id == brand) {
						this.goodsInfo.brandName = row.showName
						this.goodsInfo.brandCode = row.dcCode
					}
				})
			},
			tableRowClassName({ row, rowIndex }) {
				if (rowIndex === 1) {
					return 'warning-row';
				}
				return '';
			},
			priceCalc(price) {
				if (price) return price.toFixed(2);
			},
			// 计算折扣率
			discountRateCalc(row) {
				const goodsPrice = row.agreementPrice
				const officialPrice = row.officialPrice
				if (goodsPrice == "" || goodsPrice == 0) {
					return "wait..."
				}
				if (officialPrice == "" || officialPrice == 0 || officialPrice == null || officialPrice == undefined) {
					return "";
				}
				return (tools.accDiv(goodsPrice, officialPrice) * 100).toFixed(2) + "%"
			},
			changeCategory(params) {
				this.queryParams.primaryCategory = params.primaryCategory
				this.queryParams.secondaryCategory = params.secondaryCategory
				this.queryParams.tertiaryCategory = params.tertiaryCategory
			},
			handleOrder(key) {
				var keys = Object.keys(this.queryOrder);
				for (let i = 0; i < keys.length; i++) {
					if (keys[i] == key) {
						if (this.queryOrder[keys[i]] > 1) this.queryOrder[keys[i]] = 0;
						else this.queryOrder[keys[i]]++;
					}else {
						this.queryOrder[keys[i]] = 0;
					}
				}
				this.getList();
			}
		},
		watch: {
			goodsFailVisible(value) {
				if(value) this.goodsFailInfo = "";
			}
		}
	}
</script>

<style lang="scss" scoped>
	.divider {
		color: #ff4d4f;
		padding: 0.25em;
	}

	.table::v-deep {

		.el-table__fixed,
		.el-table__fixed-right {
			z-index: 9;
		}

		.warning-row {
			// box-shadow: inset 0px 0px 6px #ff4d4f;
		}

		.name-size {
			color: #ff4d4f;
		}


	}

	.price {
		color: #ff4d4f;
	}

	.goodsNameBox {
		overflow: hidden;
		max-width: 100%;
		white-space: nowrap;
		height: 25px;
		text-overflow: ellipsis;
	}
</style>
